package com.itguigu.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {
    @Value("${sso.server.url}")
    private String ssoServerUrl;

    /**
     * 无需登录就可以访问
     */

    @GetMapping("/hello")
    public String hello(HttpServletRequest request, @RequestParam("redirect_url") String redirect) {
          String contextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getServletPath()+request.getContextPath();
        System.out.println(contextPath+redirect);
        return "hello";
    }

    @GetMapping("/boss")
    public String employee(Model model, HttpSession session, HttpServletRequest request,@RequestParam(value = "token",required = false) String token) {
        if (!StringUtils.isEmpty(token)) {
            //去ssoserver 登陆成功跳回来 就会带上token
            //todo 去ssoserver 获取当前token 真正对应的用户信息
            session.setAttribute("loginUser","张三");

        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            //没登录,跳转登录8
            //跳转过去以后 使用url上的查询参数标识我们自己是哪个页面
            String contextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getServletPath();
            return "redirect:" + ssoServerUrl + "?redirect_url=" + contextPath;
        }
        List<String> emps = new ArrayList<>();
        emps.add("张三");
        emps.add("李四");
        model.addAttribute("emps", emps);
        return "list";
    }
}
